<?php

/**
 * Class FrontController
 */
class FrontController
{
    /**
     * @var
     */
    protected $Request;
    /**
     * @var string
     */
    protected $controller = 'Base';
    /**
     * @var string
     */
    protected $action = 'process';
    /**
     * @var array
     */
    protected $controller_params = array();

    /**
     *
     */
    public function __construct()
    {
        $this->init();
    }

    /**
     *
     */
    protected function init()
    {
        $uri_parts = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), ' /'));
        $uri_parts = array_map('strtolower', $uri_parts );
        if (!empty($uri_parts)) {
            $this->controller = ucfirst(array_shift($uri_parts));
            $this->controller_params = $uri_parts;
        }
    }

    /**
     *
     */
    public function dispatch()
    {
        try {
            if (class_exists($this->controller)) {
                $Controller = new $this->controller($this->controller_params);
                $Controller->{$this->action}();
            } else {
                throw new Exception("Call to undefined controller: {$this->controller}");
            }
        } catch (Exception $e) {
            Logger::message($e->getMessage() . '; ' . $e->getTraceAsString());
            header('Content-type: application/json');
            echo json_encode(array('internal error'));
        }
    }
}
